/**
 * @description 数据角色管理
 * @author 李艳
 */
import {Component} from "react";
import {
  findAllDataRoleGroup, findAllDataRole,
  saveDataRoleGroup, deleteDataRoleGroup, saveDataRole, deleteDataRole
} from "./DataRoleManagerService";
import React from "react";
import {Button, Col, message, Row, Input, Modal} from "antd";
import {cache, searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import SimpleTable from "../../../commons/components/SimpleTable";
import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import EditDataRoleGroupModal from "./EditDataRoleGroupModal";
import EditDataRoleModal from "./EditDataRoleModal";
import ShowConfigPage from "./ShowConfigPage";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import DetailCard from "../../../commons/components/DetailCard";
import {rowGutter} from "../../../configs/DefaultConfig";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from '../../../commons/components/CheckAuth';

const Search = Input.Search;
const confirm = Modal.confirm;

class DataRoleManagerView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "数据角色管理"}];
    this.state = {
      data: [],
      leftSelectedRow: [],
      leftSearchValue: "",
      rightSearchValue: "",
      rightData: [],
      loading: false,
      rightSelectRow: [],
      leftModalVisible: false,
      rightModalVisible: false,
      confirmLoading: false,
      isLeftAdd: true,
      isRightAdd: true
    }
  }

  onLeftModalRef = (ref) => {
    this.leftModalRef = ref;
  };
  onRightModalRef = (ref) => {
    this.rightModalRef = ref;
  };

  componentWillMount() {
    this.getData()
  };

  //请求左边table数据
  getData = (leftSearchValue) => {
    this.props.show();
    findAllDataRoleGroup().then((res) => {
      searchListByKeyWithTag(res, {keyword: leftSearchValue}, ['code', 'name']).then(searchData => {
        this.setState({data: searchData})
      })
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  onLeftSelectRow = (tableSelectRow) => {
    this.setState({leftSelectedRow: tableSelectRow})
    if (tableSelectRow[0]) {
      let param = {roleGroupId: tableSelectRow[0].id};
      this.findAllDataRole(param)
    }
  };
  //请求右边table数据
  findAllDataRole = (param, rightSearchValue) => {
    this.setState({loading: true});
    findAllDataRole(param).then((res) => {
      searchListByKeyWithTag(res, {keyword: rightSearchValue}, ['code', 'name']).then(searchData => {
        this.setState({rightData: searchData, rightSelectRow: []});
      })
    }).catch(err => {
    }).finally(() => {
      this.setState({loading: false});
    });
  };
  onAddLeftClick = () => {
    this.setState({leftModalVisible: true, isLeftAdd: true})
  };
  onEditLeftClick = (record) => {
    this.setState({leftEditData: record});
    this.setState({leftModalVisible: true, isLeftAdd: false})
  };
  handleLeftSearch = (value) => {
    searchListByKeyWithTag(this.state.data, {keyword: value}, ["code", "name"]).then(res => {
      this.setState({data: res, leftSearchValue: value})
    })
  };

  //新增或编辑点击确定按钮事件
  handleEditLeft = () => {
    //表单数据同步
    if (this.leftModalRef && this.leftModalRef.props.form) {
      this.leftModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, leftModalVisible: true});
          if (this.state.isLeftAdd) {
            delete values.id
          }
          if (cache && cache.get("Authorization") && cache.get("Authorization").tenantCode) {
            values.code = cache.get("Authorization").tenantCode + "-" + values.code
          }
          saveDataRoleGroup(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //左边数据角色组数据刷新本地数据
              if (this.state.isLeftAdd) {//新增清空查询条件
                this.getData("");
                this.setState({searchGroupValue: ''})
              } else {
                this.getData(this.state.leftSearchValue);
              }
              this.setState({confirmLoading: false, leftModalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  handleLeftModalCancel = () => {
    this.setState({leftModalVisible: false})
  };
  onDeleteLeftClick = (record) => {
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        thiz.props.show();
        deleteDataRoleGroup(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            thiz.getData(thiz.state.leftSearchValue);
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
          thiz.props.hide();
        })
      },
      onCancel() {
      },
    });
  };

  onTableSelectRow = (tableSelectRow) => {
    this.setState({rightSelectRow: tableSelectRow});
  };
  judgeLeftSelected = () => {
    if (!this.state.leftSelectedRow[0]) {
      message.error('请选择数据角色组！');
      return false;
    }
    return true;
  };
  judgeSelected = () => {
    if (!this.state.rightSelectRow[0]) {
      message.error('请选择数据角色！');
      return false;
    }
    return true;
  };
  onAddRightClick = () => {
    if (!this.judgeLeftSelected()) return;
    this.setState({rightModalVisible: true, isRightAdd: true})
  };
  onEditRightClick = (record) => {
    this.setState({rightModalVisible: true, isRightAdd: false, rightEditData: record})
  };
  handleRightSearch = (value) => {
    searchListByKeyWithTag(this.state.rightData, {keyword: value}, ["code", "name"]).then(res => {
      this.setState({rightData: res, rightSearchValue: value})
    })
  };

  //新增或编辑点击确定按钮事件
  handleEditRight = () => {
    //表单数据同步
    if (this.rightModalRef && this.rightModalRef.props.form) {
      this.rightModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, rightModalVisible: true});
          if (this.state.isRightAdd) {
            delete values.id
          }
          if (cache && cache.get("Authorization") && cache.get("Authorization").tenantCode) {
            values.code = cache.get("Authorization").tenantCode + "-" + values.code
          }
          saveDataRole(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请左边数据角色组数据刷新本地数据
              let param = {roleGroupId: this.state.leftSelectedRow[0] ? this.state.leftSelectedRow[0].id : ""};
              this.findAllDataRole(param)
              if (this.state.isRightAdd) {//新增清空查询条件
                this.findAllDataRole(param);
                this.setState({rightSearchValue: ''})
              } else {
                this.findAllDataRole(param, this.state.rightSearchValue);
              }
              this.setState({confirmLoading: false, rightModalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  handleRightModalCancel = () => {
    this.setState({rightModalVisible: false})
  };
  onDeleteRightClick = (record) => {
    this.setState({rightEditData: record})
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        thiz.props.show();
        deleteDataRole(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            let param = {roleGroupId: thiz.state.leftSelectedRow[0] ? thiz.state.leftSelectedRow[0].id : ""};
            thiz.findAllDataRole(param, thiz.state.rightSearchValue)
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
          thiz.props.hide();
        })
      },
      onCancel() {
      },
    });
  };
  onRightConfigClick = () => {
    if (!this.judgeSelected()) return;
    this.setDisplay(true)
  };

  setDisplay = (display) => {
    this.setState({isPositionConfig: display})
  };

  getPathData = () => {
    const {isPositionConfig, rightSelectRow} = this.state;
    if (isPositionConfig) {
      const path = [{name: `角色【${rightSelectRow[0].name}】`}, {name: "配置"}];
      return [...this.initPath, ...path];
    } else {
      return null;
    }
  }
  getExtra = () => {
    const {isPositionConfig} = this.state;
    if (isPositionConfig) {
      return [
        <Button key={"return"} onClick={() => this.setDisplay(false)}>返回</Button>
      ]
    }
    return null;
  }

  render() {
    const leftColumns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-QXGL-DATAROLEGROUP-EDIT">
                <a className={'row-operator-item'} onClick={() => this.onEditLeftClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-QXGL-DATAROLEGROUP-DELETE">
                <a className={'row-operator-item'} onClick={() => this.onDeleteLeftClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      }
    ];
    const rightColumns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-QXGL-DATAROLE-EDIT">
                <a className={'row-operator-item'} onClick={() => this.onEditRightClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-QXGL-DATAROLE-DELETE">
                <a className={'row-operator-item'} onClick={() => this.onDeleteRightClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      },
      {
        title: '公共角色组织机构',
        dataIndex: 'publicOrg.name',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      },
      {
        title: '公共角色用户类型',
        dataIndex: 'publicUserTypeRemark',
        width: 180
      }
    ];
    const leftTitle = () => {
      return [
        <CheckAuth operateCode="BASIC-QXGL-DATAROLEGROUP-ADD" key="addRule">
          <Button style={{marginRight: '5px'}} type={"primary"}
                  onClick={this.onAddLeftClick}>新增</Button>
        </CheckAuth>

      ]
    };

    //表头搜索框
    const leftSearch = () => {
      return [
        <Search
          key="search"
          placeholder="输入代码或名称查询"
          onSearch={value => this.handleLeftSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    const title = () => {
      return [
        <CheckAuth operateCode="BASIC-QXGL-DATAROLE-ADD" key="addRule">
          <Button className={"primaryButton"} type={"primary"}
                  onClick={this.onAddRightClick}>新增</Button>
        </CheckAuth>,
        <CheckAuth operateCode="BASIC-QXGL-DATAROLE-CONFIG" key="config">
          <Button style={{marginRight: '5px'}}
                  onClick={this.onRightConfigClick}>配置</Button>
        </CheckAuth>

      ]
    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入代码或名称查询"
          onSearch={value => this.handleRightSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    return (
      <HeadBreadcrumb
        pathData={this.getPathData()}
        rightExtra={this.getExtra()}
        className={this.state.isPositionConfig ? "" : "allocation-page"}
        style={this.state.isPositionConfig ? {
          margin: 0,
          padding: 0,
          height: "100%",
          overflow: "hidden"
        } : {overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{display: this.state.isPositionConfig ? "none" : "block"}}>
          {/*左边控件*/}
          <Col span={9} style={{height: "100%"}}>
            <DetailCard title="数据角色组" style={{height: "100%"}}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{leftTitle()}</div>
                <div className={'tbar-search-box'}>{leftSearch()}</div>
              </div>
              <SimpleTable
                inCard={true}
                data={this.state.leftSearchValue ? this.state.data.filter(item => item.tag === true) : this.state.data}
                columns={leftColumns}
                loading={this.state.loading}
                onSelectRow={this.onLeftSelectRow}
              />
            </DetailCard>
          </Col>
          {/*右边的表格控件*/}
          <Col span={15}>
            <DetailCard title="数据角色" className={"child-card"}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{title()}</div>
                <div className={'tbar-search-box'}>{search()}</div>
              </div>
              <SimpleTable
                data={this.state.rightSearchValue ? this.state.rightData.filter(item => item.tag === true) : this.state.rightData}
                columns={rightColumns}
                loading={this.state.loading}
                onSelectRow={this.onTableSelectRow}
                rowsSelected={this.state.rightSelectRow}
              />
            </DetailCard>

            <EditDataRoleGroupModal
              modalVisible={this.state.leftModalVisible}
              confirmLoading={this.state.confirmLoading}
              handleOk={this.handleEditLeft}
              handleCancel={this.handleLeftModalCancel}
              onRef={this.onLeftModalRef}
              defaultValue={this.state.leftEditData ? this.state.leftEditData : {}}
              isAdd={this.state.isLeftAdd}
            />
            {this.state.rightModalVisible && <EditDataRoleModal
              modalVisible={this.state.rightModalVisible}
              confirmLoading={this.state.confirmLoading}
              handleOk={this.handleEditRight}
              handleCancel={this.handleRightModalCancel}
              onRef={this.onRightModalRef}
              defaultValue={!this.state.isRightAdd && this.state.rightEditData ? this.state.rightEditData : {}}
              dataRoleGroup={this.state.leftSelectedRow[0] ? this.state.leftSelectedRow[0] : {}}
              isAdd={this.state.isRightAdd}
            />}
          </Col>
        </Row>
        {
          this.state.isPositionConfig ? <ShowConfigPage
            selectedRole={this.state.rightSelectRow[0] ? this.state.rightSelectRow[0] : {}}
          /> : null
        }
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(DataRoleManagerView))
